package me.lc.linklink.util;

import me.lc.linklink.core.GameSystem;
import me.lc.linklink.sprite.LLKBlock;

public class LLKLogicHelper {
	private static LLKBlock[][] blocks;

	public static boolean CanEliminate(LLKBlock[][] gameData, int x1, int y1,
			int x2, int y2) {
		blocks = gameData;
		return IsLined(x1, y1, x2, y2) || IsOneConner(x1, y1, x2, y2)
				|| IsTwoConner(x1, y1, x2, y2);
	}

	private static boolean IsTwoConner(int x1, int y1, int x2, int y2) {
		for (int i1 = 0; i1 < GameSystem.GameRows + 2; i1++) {
			for (int j1 = 0; j1 < GameSystem.GameColumns + 2; j1++) {
				for (int i2 = 0; i2 < GameSystem.GameRows + 2; i2++) {
					for (int j2 = 0; j2 < GameSystem.GameColumns + 2; j2++) {
						if (blocks[i1][j1].getBlockItemIndex() != -1) {
							continue;
						}
						if (blocks[i2][j2].getBlockItemIndex() != -1) {
							continue;
						}
						if (IsLined(x1, y1, i1, j1) && IsLined(i1, j1, i2, j2)
								&& IsLined(i2, j2, x2, y2))
							return true;
					}
				}
			}
		}
		return false;
	}

	private static boolean IsOneConner(int x1, int y1, int x2, int y2) {
		for (int i = 0; i < GameSystem.GameRows + 2; i++) {
			for (int j = 0; j < GameSystem.GameColumns + 2; j++) {
				if (blocks[i][j].getBlockItemIndex() != -1) {
					continue;
				}
				if (IsLined(x1, y1, i, j) && IsLined(i, j, x2, y2)) {
					return true;
				}
			}
		}
		return false;
	}

	private static boolean IsLined(int x1, int y1, int x2, int y2) {
		int max, min, flag;
		if (x1 == x2) {
			if (y1 > y2) {
				max = y1;
				min = y2;

			} else {
				max = y2;
				min = y1;
			}
			flag = 1;
			for (int i = min + 1; i < max; i++) {
				if (blocks[x1][i].getBlockItemIndex() != -1) {
					flag = 0;
					break;
				}
			}
			if (flag == 1)
				return true;
		} else if (y1 == y2) {
			if (x1 > x2) {
				max = x1;
				min = x2;

			} else {
				max = x2;
				min = x1;
			}
			flag = 1;
			for (int i = min + 1; i < max; i++) {
				if (blocks[i][y1].getBlockItemIndex() != -1) {
					flag = 0;
					break;
				}
			}
			if (flag == 1)
				return true;
		}

		return false;
	}
}
